/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.model.template;

import offset.nodes.client.model.XmlCharacterFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 *
 * @author Walter Lütgenau
 */
public abstract class AbstractTreeDefinitionWriter {
    ContentHandler handler;
    XmlCharacterFilter filter;
    
    public AbstractTreeDefinitionWriter(ContentHandler handler) {
        this.handler = handler;
        this.filter = new XmlCharacterFilter(handler);
    }

    protected void characters(char[] chars, int start, int length) throws SAXException {
        filter.characters(chars, start, length);
    }

    protected void endElement(String name) throws SAXException {
        handler.endElement("", "", name);
    }

    public void print(DefaultMutableTreeNode definition) throws Exception {
        handler.startDocument();
        printNode(definition);
        handler.endDocument();
    }

    /**
     * Print the node and its attributes, including the child nodes
     *
     * @param node the node
     * @throws org.xml.sax.SAXException
     */
    protected abstract void printNode(DefaultMutableTreeNode node) throws Exception;

    protected void startElement(String name, Attributes atts) throws SAXException {
        handler.startElement("", "", name, atts);
    }

    protected String toPrefixName(QName name) throws Exception {
        String prefixName = SimpleNamespaceRegistry.getInstance().getPrefix(name.getNamespaceURI()) + ":" + name.getLocalName();

        return prefixName;
    }

    protected void addAttribute(AttributesImpl atts, String name, String value) {
        atts.addAttribute("", "", name, "CDATA", value);
    }

}
